<template>
    <div class="addMerchantBox" v-loading="loading">
        <el-button class="el-icon-arrow-left" size="mini" type="primary" style="margin-bottom:10px;"
                   @click="handBackList">返回
        </el-button>
        <el-form ref="form">
            <el-input v-model="initial_data.id" type="hidden"></el-input>
            <el-form-item label="管理员密码">
                <el-input
                        v-model="initial_data.password"
                        placeholder="修改密码则填写，不修改密码则不填写"
                        style="width:300px"
                ></el-input>
            </el-form-item>

            <el-form-item label="管理员头像">
                <div class="picUpload" style="display:flex;flex-direction:row">
                    <div>
                        <div>
                            <el-upload
                                    :http-request="handlePictureCardPreview"
                                    :multiple="false"
                                    action
                                    list-type="picture-card"
                                    name="avatar"
                                    ref="businessLicenseUpload"
                            >
                                <i class="el-icon-plus"></i>
                            </el-upload>
                            <el-dialog
                                    :modal="false"
                                    :center="true"
                                    :show-close="false"
                                    class="commonVisible"
                                    :visible.sync="avatarVisible"
                                    :fullscreen="true"
                            >
                                <img alt class :src="initial_data.avatar" v-show="avatarVisible">
                                <span class="hoverBox" @click="avatarVisible=false" v-show="avatarVisible">
                  <span class="deleteIcon">
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
                            </el-dialog>
                        </div>
                    </div>
                </div>
            </el-form-item>

            <el-form-item label="角色">
                <el-select
                        multiple="multiple"
                        v-model="initial_data.role"
                        placeholder="请选择角色（可多选）"
                        style="width:300px"
                        @change="rolesFn($event)"
                >
                    <el-option v-for="(item) in rolesList" :key="item.id" :label="item.name"
                               :value="item.id"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="权限">
                <el-select
                        multiple="multiple"
                        style="width:300px"
                        v-model="initial_data.permissions"
                        placeholder="请选择权限（可多选）"
                >
                    <el-option
                            v-for="(item) in permissionsList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                    ></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="状态">
                <el-switch v-model="initial_data.status" active-text="禁用" inactive-text="正常"></el-switch>
            </el-form-item>
        </el-form>

        <div class="submitBtnBox">
            <el-button class="submitBtn" @click="submitFn" type="primary">确认添加</el-button>
        </div>
    </div>
</template>

<script>
    export default {
        name: "permission-updateUser",
        components: {},
        data() {
            return {
                avatarVisible: true,
                loading: false,
                rolesList: [],
                permissionsList: [],
                dialogImageUrl: "",
                businessLicenseAction: "business_license",
                addrOptions: [],
                initial_data: []
            };
        },
        methods: {
            //初始数据
            defaultFn() {
                this.loading = true;
                this.$http
                    .get("/web/user/info", {
                        params: {
                            token: localStorage.getItem("user_token"),
                            id: this.$route.query.id
                        }
                    })
                    .then(response => {
                        if (response.data.status === "success") {
                            this.initial_data = response.data.data;
                            this.initial_data.token = localStorage.getItem("user_token");
                            this.initial_data.status = this.initial_data.status == 1 ? true : false;
                            this.loading = false;
                        }
                    })
                    .catch(error => {
                        console.log("error:", error);
                    });
            },
            //获取角色下拉内容
            getRolesFn() {
                this.$http
                    .get("/web/user/roles/list", {
                        params: {
                            token: localStorage.getItem("user_token"),
                            pageSize: 999
                        }
                    })
                    .then(response => {
                        if (response.data.status === "success") {
                            this.rolesList = response.data.data.list;
                        }
                    })
                    .catch(error => {
                        console.log("error:", error);
                    });
            },
            getPermissionsFn() {
                this.$http
                    .get("/web/user/permissions/no/page/list", {
                        params: {
                            token: localStorage.getItem("user_token")
                        }
                    })
                    .then(response => {
                        if (response.data.status === "success") {
                            this.permissionsList = response.data.data;
                        }
                    })
                    .catch(error => {
                        console.log("error:", error);
                    });
            },
            //上传图片:folder是传给服务的文件名,用作图片分类
            handleAvatarSuccess(res, file) {
                console.log(file);
                this.initial_data.avatar = URL.createObjectURL(file.raw);
            },
            beforeAvatarUpload(file) {
                console.log(file);
                const isPNG = file.type === "image/png";
                const isJPEG = file.type === "image/jpeg";

                if (!(isJPG || isPNG || isJPEG)) {
                    this.$message.error("上传头像图片只能是 JPG 格式!");
                }
                return isPNG && isJPEG;
            },
            handlePictureCardPreview(file) {
                this.loading = true;
                let imageFile = file.file;
                let formData = new FormData();
                formData.append("image", imageFile);
                formData.append("action", file.filename);
                this.$http
                    .post("/api/tool/ali/upload/image", formData)
                    .then(response => {
                        if (file.filename == "avatar") {
                            this.initial_data.avatar = response.data.data;
                        }
                        this.loading = false;
                    })
                    .catch(error => {
                        console.log("图片上传失败");
                    });
            },

            submitFn() {
                this.initial_data.status = this.initial_data.status === true ? 1 : 0;
                this.loading = true;
                this.$nextTick(() => {
                    this.$http
                        .post("/web/user/update", this.initial_data)
                        .then(response => {
                            if (response.data.status == "success") {
                                this.$message({
                                    message: "修改成功",
                                    duration: 6000
                                });

                                this.$router.push({
                                    name: "permissionUser"
                                });
                            } else {
                                this.$message({
                                    message: "修改失败，原因：" + response.data.failedMsg,
                                    duration: 6000
                                });
                            }
                            this.loading = false;
                        })
                        .catch(error => {
                            this.$message({
                                message: "修改失败，原因：" + error,
                                duration: 6000
                            });
                            this.loading = false;
                        });
                });
            },

            handBackList() {
                this.$router.push({name: "permissionUser"});
            },
        },
        mounted() {
            this.getRolesFn();
            this.defaultFn();
            this.getPermissionsFn();
            this.$refs.businessLicenseUpload.submit();
        }
    };
</script>

<style scoped lang="scss">
    @import "./user.scss";
</style>
